package com.dpiinc.TechPage.adapter
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.dpiinc.TechPage.R
import com.dpiinc.TechPage.repository.NetworkState
import com.dpiinc.TechPage.room.bean.NoteEntity
import com.dpiinc.TechPage.widget.swipemenu.SwipeMenuLayout
import com.bumptech.glide.RequestManager

/**
 * 笔记列表 Adapter
 * Created by X on 2018/7/1.
 */
class NoteListAdapter(
        private val acticity: AppCompatActivity,
        private val glide: RequestManager,
        private val retryCallback: () -> Unit)
    : PagedListAdapter<NoteEntity, RecyclerView.ViewHolder>(NOTE_COMPARATOR) {

    var isSearchMode = false
    var keyword: String? = null
    var hideTopDivider = false

    private var networkState: NetworkState? = null
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (getItemViewType(position)) {
            R.layout.note_list_item -> {
                (holder as NoteItemViewHolder).bind(acticity, getItem(position), keyword)
              //  holder.divider.visibility = if (position == 0 && hideTopDivider) View.GONE else View.VISIBLE
                (holder as NoteItemViewHolder).setOnSwipeListener(object : NoteItemViewHolder.onSwipeListener {
                    override fun onClickShare(pos: Int,note: NoteEntity) {
                        mOnSwipeListener?.onClickShare(pos,note)
                    }

                    override fun onClickDelete(pos: Int) {
                        mOnSwipeListener?.onClickDelete(pos)
                    }
                })
            }
            R.layout.network_state_item -> (holder as NetworkStateItemViewHolder).bindTo(
                    networkState)
        }
    }

    override fun onBindViewHolder(
            holder: RecyclerView.ViewHolder,
            position: Int,
            payloads: MutableList<Any>) {
        if (payloads.isNotEmpty()) {
            val item = getItem(position)
            (holder as NoteItemViewHolder).updateNote(item)
        } else {
            onBindViewHolder(holder, position)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            R.layout.note_list_item -> {
               val noteItemViewHolder = NoteItemViewHolder.create(parent, glide)
                (noteItemViewHolder.itemView as SwipeMenuLayout).isSwipeEnable = !isSearchMode
                noteItemViewHolder
            }
            R.layout.network_state_item -> NetworkStateItemViewHolder.create(parent, retryCallback)
            else -> throw IllegalArgumentException("unknown view type $viewType")
        }
    }

    private fun hasExtraRow() = networkState != null && networkState != NetworkState.LOADED

    override fun getItemViewType(position: Int): Int {
        return if (hasExtraRow() && position == itemCount - 1) {
            R.layout.network_state_item
        } else {
            R.layout.note_list_item
        }
    }

    override fun getItemCount(): Int {
        return super.getItemCount() + if (hasExtraRow()) 1 else 0
    }

    fun setNetworkState(newNetworkState: NetworkState?) {
        val previousState = this.networkState
        val hadExtraRow = hasExtraRow()
        this.networkState = newNetworkState
        val hasExtraRow = hasExtraRow()
        if (hadExtraRow != hasExtraRow) {
            if (hadExtraRow) {
                notifyItemRemoved(super.getItemCount())
            } else {
                notifyItemInserted(super.getItemCount())
            }
        } else if (hasExtraRow && previousState != newNetworkState) {
            notifyItemChanged(itemCount - 1)
        }
    }

    companion object {
        private val PAYLOAD = Any()
        val NOTE_COMPARATOR = object : DiffUtil.ItemCallback<NoteEntity>() {
            override fun areContentsTheSame(oldItem: NoteEntity, newItem: NoteEntity): Boolean =
                    oldItem.modifyTime == newItem.modifyTime

            override fun areItemsTheSame(oldItem: NoteEntity, newItem: NoteEntity): Boolean =
            //这里暂时不做部分刷新了，只要modifyTime变了，就视为一个新item，刷新整个itemView
//                    oldItem.noteId == newItem.noteId
                    oldItem.modifyTime == newItem.modifyTime

            override fun getChangePayload(oldItem: NoteEntity, newItem: NoteEntity): Any? {
//                return if (same(oldItem, newItem)) {
//                    PAYLOAD
//                } else {
//                    null
//                }
                return PAYLOAD
            }
        }
    }

    private var mOnSwipeListener: onSwipeListener? = null

    interface onSwipeListener {
        fun onClickShare(pos: Int,note: NoteEntity)

        fun onClickDelete(pos: Int)
    }

    fun setOnSwipeListener(mOnSwipeListener: onSwipeListener) {
        this.mOnSwipeListener = mOnSwipeListener
    }
}
